package com.classnet.mail;

import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

/**
 *
 * @author karltinawi
 * @version 1.0
 */
public class MailMessage {
    
    private String subject;
    private String message;
    private InternetAddress sender;
    private InternetAddress[] recipients;
    private RecipientType recType;
    
    public MailMessage(InternetAddress from, InternetAddress[] recipients) throws AddressException {
        setSubject(null);
        setMessage(null);
        setSender(from);
        setRecipients(recipients);
        setRecipientType(null);
    }

    public void setRecipients(InternetAddress[] rec) {
        //Check if rec is null.
        if(rec == null) rec = new InternetAddress[0];
        
        //Find the last non-null email address.
        int last = rec.length - 1;        
        while(last >= 0 && rec[last] == null) last --;
        
        //Remove all null or empty email address by replacing them with the last
        //non-null email address in the list.
        for(int i = 0; i <= last; i ++) {
            if(rec[i] == null || rec[i].getAddress().trim().length() == 0) {
                rec[i] = rec[last];
                rec[last --] = null;
                setRecipients(rec);
            }
        }        
        if(last < 0) last = 0;
        else last ++;
        
        recipients = new InternetAddress[last];
        for(int i = 0; i < last; i ++) recipients[i] = rec[i];
    }
    
    public void setSender(InternetAddress from) throws AddressException {
        if(from == null) throw new NullPointerException("No Sender Specified.");
        else sender = from;
    }

    public void setSubject(String sub) {
        if(sub == null) subject = "";
        else subject = sub;
    }

    public void setMessage(String mes) {
        if(mes == null) message = "";
        else message = mes;
    }
    
    private void setRecipientType(RecipientType rt) {
       if(rt == null) recType = RecipientType.TO;
       else recType = rt;
    }
    
    public InternetAddress[] getRecipients() {
        return recipients;
    }
    
    public InternetAddress getSender() {
        return sender;
    }
    
    public String getSubject() {
        return subject;
    }
    
    public String getMessage() {
        return message;
    }
    
    public RecipientType getRecipientType() {
        return recType;
    }
}